package com.homedo.async.mysql.support.mapper.util;

import com.homedo.plainly.logger.Logger;
import com.homedo.plainly.logger.LoggerFactory;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.SqlConnection;
import io.vertx.sqlclient.Tuple;
import reactor.core.publisher.Mono;
import reactor.core.publisher.MonoSink;

import java.util.List;

/**
 * @author jgshun
 * @date 2020/3/17 12:08 PM
 */
public abstract class CreateMono4AffectedNumberUtil {
    private static final Logger _LOGGER = LoggerFactory.getLogger(CreateMono4AffectedNumberUtil.class);

    public static Mono<Long> create(Object[] prepareSqlArgs, Pool pool, SqlConnection connection) {
        return Mono.create(sink -> {
            if (connection == null) {
                pool.getConnection(connRes -> {
                    if (connRes.succeeded()) {
                        SqlConnection newConnection = connRes.result();

                        create(prepareSqlArgs, newConnection, true, sink);
                    } else {
                        sink.error(connRes.cause());
                    }
                });
            } else {
                create(prepareSqlArgs, connection, false, sink);
            }
        });

    }

    private static void create(Object[] prepareSqlArgs, SqlConnection connection, boolean close, MonoSink<Long> sink) {

        connection.preparedQuery(prepareSqlArgs[0].toString(), Tuple.tuple((List<Object>) prepareSqlArgs[1]), res -> {
            if (res.succeeded()) {
                sink.success(Long.valueOf(res.result().rowCount()));
            } else {
                sink.error(res.cause());
                _LOGGER.error("Failure: {}", res.cause().getMessage(), res.cause());
            }

            if (close) {
                connection.close();
            }
        });

    }

}
